package model

import "github.com/jinzhu/gorm"

func (order *Order) OrderVersion1(userId int, goodsId int, number int) bool {
	tx := db.Begin()
	// 减库存
	var goods Goods
	rowsAffected := tx.Model(&goods).Where("id = ?", goodsId).Where("stock - ? >= 0", number).UpdateColumn("stock", gorm.Expr("stock - ?", number)).RowsAffected
	if rowsAffected == 0 {
		tx.Rollback()
		return false
	}

	// 下单
	order.UserId = userId
	order.GoodsId = goodsId
	order.Number = number
	if err := tx.Create(order).Error; err != nil {
		tx.Rollback()
		return false
	}

	tx.Commit()
	return true
}

